delete_btn = "<button class='delete'>删除</button>"
change_btn = "<button class='change'>修改</button>"
colum_list = ['hostname', 'ip', 'username', 'password', delete_btn, change_btn]
colum_value_list = colum_list.slice(0,4)
form0 = document.getElementById('add_form')
form1 = document.getElementById('change_form')
beijing = document.getElementsByClassName('beijing')[0]
table = document.getElementsByTagName('table')[0];

//行收据填充
function new_data(par, form_type) {
    for (var i = 0; i < colum_list.length; i++) {
        var colum_new = document.createElement('td');
        par.append(colum_new)
        switch (i){
            case 4:
                colum_new.innerHTML = delete_btn;
                colum_new.firstChild.setAttribute('onclick', 'deletebtn(this)');
                break;
            case 5:
                colum_new.innerHTML = change_btn;
                colum_new.firstChild.setAttribute('onclick', 'changebtn(this)');
                break;
            default:
                colum_new.innerHTML = document.getElementById(form_type + '_' + colum_list[i]).value;
                break;
        }
        }
}
//数据增加时使用的表单提交
form0.onsubmit=function (event) {
    // 添加行
    var tr = document.createElement('tr');
    table.append(tr);
    // 行数据填充
    new_data(tr, 'add')
    // exit
    form0.classList.add('hide');
    beijing.classList.add('hide');
    event.preventDefault();
}

//添加按钮
var add=document.getElementById('tianjia')
add.onclick=function () {
    beijing.classList.remove('hide');
    form0.classList.remove('hide');
}

//删除按钮
function deletebtn(e) {
    e.parentElement.parentElement.parentElement.removeChild(e.parentElement.parentElement);
}

//修改按钮
function changebtn(e) {
    form1.classList.remove('hide');
    beijing.classList.remove('hide');
    // 定位操作的数据行
    tr = e.parentElement.parentElement
    // 将表单中的数据赋值给修改操作使用的表格
    for (var i = 0; i < colum_value_list.length; i++) {
        document.getElementById('change_' + colum_value_list[i]).value = tr.children[i].innerHTML
    };
    //数据修改时使用的表单提交
    form1.onsubmit = function (event) {
        var tr_new =  document.createElement('tr');
        // 表格替换
        table.replaceChild(tr_new, tr);
        // 行数据填充
        new_data(tr_new, 'change');
        beijing.classList.add('hide');
        form1.classList.add('hide');
        event.preventDefault();
    }
}
